<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\Message;
use App\Repository\MessageRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use function Doctrine\ORM\QueryBuilder;

class ApiMessageController extends BaseController4Restful
{
    /**
     * @Route("/api/messages", name="apiGetMessages",methods={"GET","POST"})
     */
    public function apiGetMessages(MessageRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $Message Message*/
                $Message = $this->createEntity($data,Message::class);
                $this->myEm()->persist($Message);$this->myEm()->flush();
                return $this->json_out(200,"创建成功", $Message);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array(),array(),$limit,$offset);
                $this->setGroups("app","cat");

                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/messages/{id}", name="apiAddMessages",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateMessages(Message $Message,Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($Message);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $Message Message*/
                $Message = $this->updateEntity($data,Message::class,$Message);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($Message);$this->myEm()->flush();
        return $this->json_out(200,"获取成功", $Message);
    }

    /**
     * @Route("/api/my/messages", name="apiGetUserMessages",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiGetUserMessages(MessageRepository $repository)
    {
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        $user = $this->needToBeUser();
        $qb = $repository->createQueryBuilder("A");
        $qb->select("A");
        $qb->where(
            $qb->expr()->orX(
                $qb->expr()->eq("A.toid",$user->getId())
                ,$qb->expr()->eq("A.toid",0)
            )
        );
        $qb->orderBy("A.createAt","DESC");
        $qb->setFirstResult($page * 10 - 10)->setMaxResults(10);
        $list = $qb->getQuery()->execute();
        $this->setGroups("app","cat");

        return $this->json_out(200,"获取成功", $list);
    }

}
